import React, { Component } from 'react'
import moment from 'moment'
import { Icon } from 'tinper-bee'
import { Button, ButtonGroup } from 'tinper-bee';
import Tooltip from 'bee-tooltip';
import 'bee-tooltip/build/Tooltip.css';
import { vendorsFmtDate } from "./../../utils/config.js";
import "./index.less";
import objectPath from 'object-path';
import {Map , is} from "Immutable";
//import {number, array, string} from "prop-types"
import PropTypes from "prop-types";

export default class Gantt extends Component {
  constructor(props) {
    super(props)
    this.state = {
      status: 'day', //"d","m","y"，
      year: [],//涉及的年的数组
      data: [],
      month :[], 
      minimize : true
    }
  }

  componentDidMount() {
    this.init.call(this)
  }

  //获取涉及的年，并且排序以及去重
  init = () => {
    let {
      data = [],
    
    } = this.props;

    let {
      year, month
    } = this.getYear.call(this, data, [], []);
   
    if (!data.length) {
      year = [new Date().getFullYear()];//若没有data，则设默认是当前年，
      month = [new Date().getMonth()+1];//若没有data，则设默认是当前月，
    }
    this.setState({
      year: [... new Set(year)],
      month :[... new Set(month)], 
      data
    })
  }
  //没判断好，会导致元素没挂在DOM树上， 间接影响其他功能
  shouldComponentUpdate(nextProps,nextState){
    const nextPropsObj = Map(nextProps).toJS();
    const thisPropsObj = Map(this.props).toJS();
    const nextStateObj = Map(nextState).toJS();
    const thisStateObj = Map(this.state).toJS();

    if(!is(nextPropsObj, thisPropsObj)){
      return true
    }
    if(!is(nextStateObj, thisStateObj)){
      return true
    }
    return false
  }

  componentWillReceiveProps(nextProps) {
    
    if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data) || nextProps.data.length) {
      if(JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data)){
        this.setState({
          status:'day'
        })
      }
      this.init.call(this);
    }
  }

  //获取涉及的年，并且排序以及去重
  getYear = (data, yearArr = [], monthOfYear = []) => {
    let {
      planStartDate = "planStartDate",
      planEndDate = "planEndDate"
    } = this.props.contentKey;

    //以年为维度，获取数据里的年份
    data.map(item => {
      //当前数据的开始和结束是否是同一年，是：保存一个到年的数组中；否，两个按序存入到年的数组中
      if (moment(vendorsFmtDate(item[planStartDate])).isSame(vendorsFmtDate(item[planEndDate]), 'year')) {
        //存储月
        if(moment(vendorsFmtDate(item[planStartDate])).isSame(vendorsFmtDate(item[planEndDate]), 'month')){
          monthOfYear = monthOfYear.concat([moment(vendorsFmtDate(item[planStartDate])).format("YYYY-M")]);
        }else{
          monthOfYear = monthOfYear.concat([moment(vendorsFmtDate(item[planStartDate])).format("YYYY-M"), moment(vendorsFmtDate(item[planEndDate])).format("YYYY-M")]);
        }

        yearArr = yearArr.concat([moment(vendorsFmtDate(item[planStartDate])).get('year')]);

      } else {
        //存储月
        if(moment(vendorsFmtDate(item[planStartDate])).isSame(vendorsFmtDate(item[planEndDate]), 'month')){
          monthOfYear = monthOfYear.concat([moment(vendorsFmtDate(item[planStartDate])).format("YYYY-M")]);
        }else{
          monthOfYear = monthOfYear.concat([moment(vendorsFmtDate(item[planStartDate])).format("YYYY-M"), moment(vendorsFmtDate(item[planEndDate])).format("YYYY-MM")]);
        }
       
        yearArr = yearArr.concat([moment(vendorsFmtDate(item[planStartDate])).get('year'), moment(vendorsFmtDate(item[planEndDate])).get('year')]);
      }
      //排序，升序（小在前，大的在后）
      monthOfYear = monthOfYear.sort((a, b) => {
        return a - b
      })
      //排序，升序（小在前，大的在后）
      yearArr = yearArr.sort((a, b) => {
        return a - b
      })

      if (item.children && item.children.length) {
        this.getYear.call(this, item.children, yearArr, monthOfYear)
      }
    })
    return {year : yearArr, month: monthOfYear}
  }

  /**
   * 递归出年月日的树
   * time:[]//年||月||日有多少个
   * data:每次遍历都要存储的数据， 最终形成一个树
   * curDeep: 当前是第几层遍历。
   * curYear : 当是月或者日的维度时， 要记录最外层遍历的年是哪一年， 用来获取当前年， 的当前月有多少天。
   * curMonth = '01',
   * height = 85，根据父组件的头部高度来获取的，默认85
   */
  time = (
    time = [],
    data = [],
    curDeep = 0,
    curYear = '2020',
    curMonth = '01',
    height = 85,
    month = ['2020-1']
  ) => {
    let { status } = this.state

    time.map((item, index) => {
      curYear = curDeep === 0 ? item : curYear
      curMonth = curDeep === 1 ? (Number(month[0].split("-")[0]) === curYear ? Number(item) + index : index + 1): curMonth
      data.push(
        <div
          className = {"time"}
          style={{
            borderLeft: index === 0 ? 0 : '1px solid #dddee1',
            borderRight: time.length - 1 === index ? 0 : '1px solid #dddee1',
            borderRight: '0px',
            borderTop: curDeep === 0 ? '0px' : '1px solid item',
            width: status === "day" && curDeep === 2 ? 50 : status === "month" && curDeep === 1 ? "auto" : "auto",
           flexBasis : status === "day" && curDeep === 2 ? 50 : status === "month" && curDeep === 1 ? "auto" : "auto",
          }}
          id={
            curDeep === 0
              ? curYear +'-row'+ this.props.index
              : curDeep === 1
                ? (Number(month[0].split("-")[0]) === curYear ? curYear + '-' + (Number(item) + index) +'-row'+ this.props.index: curYear + '-' + (index + 1) + '-row'+ this.props.index)
                : curYear + '-' + curMonth + '-' + (index + 1)+ '-row'+ this.props.index
          }
        >
          <div
            className={'headerText'}
            style={{
              height: height,
            }}
          >
            {curDeep === 0
              ? item + '年'
              : curDeep == 1
                ? (Number(month[0].split("-")[0]) === curYear ? Number(item) + index +'月' : index + 1 +'月')
                : index + 1}
          </div>

          { //1.维度是年：不走递归；2.维度是月：深度为0时，走递归；3.维度是日：深度不等于2时走递归；
            ( (curDeep !== 2 && status === 'day') || (curDeep === 0 && status === 'month') ) && 
              (<div
                  className={'headerMap'}
                >
                  {this.time( 
                    //维度是月：深度为0。自动充满存在月，维度是日：深度不等于0。自动充满当前月的天数，
                    curDeep === 0 ? new Array(index === 0? 12- month[0].split("-")[1] + 1 : 12).fill(month[0].split("-")[1]): new Array(moment(curYear + '-' + curMonth, 'YYYY-MM').daysInMonth()).fill(1),
                    data[index],
                    curDeep + 1,//当前深度，月和日的时候会有，由于年不会在递归，所以不会存在。
                    curYear,
                    curMonth,
                    height,
                    month
                  )}
                </div>)
          }
        </div>
      )
    })

    return data
  }

  header = () => {
    let data = [],
      { year, status, month} = this.state,
      height = document.getElementsByClassName("u-table-thead")[0].offsetHeight - 3; //表头的高-3是因为有border

    height = status === "day" ? height / 3 : status === "month" ? height / 2 : height;//根据维度，平均
    data = this.time(year, data, 0, "2020", "01", height, month);//构建头部日期元素树

    return data
  }

  //维度
  show = id => {
    if (id === this.state.status) {
      return
    }
    this.setState({
      status: id
    })
  }

  maxmize = ()=>{
    this.setState({
      minimize : false
    })
    let {
      index = 0,
      classNameLeftEle = 'project-table-0',
    } = this.props;

    document.getElementsByClassName(`ganttBox-${index}`)[0].style.width = "100%";
    document.getElementsByClassName(classNameLeftEle)[0].childNodes[0].style.width = "0px"
  }
  minimize = ()=>{
    this.setState({
      minimize : false
    })
    let {
      index = 0,
      classNameLeftEle = 'project-table-0',
    } = this.props;

    document.getElementsByClassName(`ganttBox-${index}`)[0].style.width = "48%";
    document.getElementsByClassName(classNameLeftEle)[0].childNodes[0].style.width= "48%";
  }
  render() {
    let { 
      status, 
      year, 
      data ,
      month
    } = this.state,
    {
      onExpand,
      expandRecord,
      index = 0,
      classNameLeftEle = 'project-table-0',
    } = this.props;

    return (
      <div style={{ ...this.props.style }} className={`ganttBox ganttBox-${index}`} >
        <div className={"header-button"}>
          <ButtonGroup className={'switchButtonGroup'}>
            <Button
              onClick={() => {
                this.show('year')
              }}
              colors={status === 'year' && "primary"}
              className={`switchButton ${status === 'year' && 'activedButton'}`}
              size='sm'
              id={'year'+'-row'+index}
            >
              年
            </Button >
            <Button
              onClick={() => {
                this.show('month')
              }}
              colors={status === 'month' && "primary"}
              className={`switchButton ${status === 'month' && 'activedButton'}`}
              size='sm'
              id={'month'+'-row'+index}
            >
              月
            </Button >
            <Button
              onClick={() => {
                this.show('day')
              }}
              colors={status === 'day' && "primary"}
              className={`switchButton ${status === 'day' && 'activedButton'}`}
              size='sm'
              id={'day'+'-row'+index}
            >
              日
            </Button >
          </ButtonGroup >
          {
            document.getElementsByClassName(`ganttBox-${index}`)[0]&& document.getElementsByClassName(`ganttBox-${index}`)[0].style.width === "48%" ? 
              <Icon onClick = {this.maxmize} style={{padding:'4px 5px'}} type='uf-maxmize' ></Icon>
            : document.getElementsByClassName(`ganttBox-${index}`)[0]&& document.getElementsByClassName(`ganttBox-${index}`)[0].style.width === "100%" ? 
              <Icon  size='sm' onClick = {this.minimize} style={{padding:'4px 5px'}} type="uf-minimize" />
            : null
          }
        </div>
        
        <div
          id={'gantt'+'-row' +index}
          className={this.props.className}
          className={'gantt'}
          style={{
            height: data.length ? document.getElementsByClassName(classNameLeftEle)[0].childNodes.length&& document.getElementsByClassName(classNameLeftEle)[0].childNodes[0] ?document.getElementsByClassName(classNameLeftEle)[0].childNodes[0].offsetHeight : 164: 164
          }}
        >
          <div
            id={`header-row${index}`}

            className={"u-table-thead header"}

          >
            {year.length ? this.header() : <div className={"noContent"}>暂无数据</div>}

          </div>

          <div className="u-table-tbody ganttContent">
            {data.length ?
              <GanttContent
                data={data}
                status={status}
                onExpand={onExpand}
                expandRecord={expandRecord}
                year={year}
                month = {month}
                index = {index}
                contentKey={{ ...this.props.contentKey }}
              /> : <div className={"noContent"}>暂无数据</div>
            }

          </div>
        </div>
      </div>
    )
  }
}

Gantt.propTypes = {
  data : PropTypes.array.isRequired,
  contentKey : PropTypes.object.isRequired,
  onExpand : PropTypes.bool.isRequired,
  expandRecord : PropTypes.object.isRequired,
  index : PropTypes.number.isRequired
}
Gantt.defaultProps = {
  data : [],
  contentKey : {},
  onExpand : false,
  expandRecord : {},
  index : 0
}

class  GanttContent extends React.Component {
  constructor(props) {
    super(props)
  }

  componentWillReceiveProps(nextProps) {

    if (nextProps && nextProps.expandRecord && Object.keys(nextProps.expandRecord).length) {

      if (!nextProps.onExpand || nextProps.onExpand) {
        let display = 'none';
        if (nextProps.onExpand) {
          display = "flex"
        } else {
          display = "none"
        }
       
        nextProps.expandRecord.children.map((item) => {
          if((nextProps.status !== this.props.status) && document.getElementById(item[nextProps.contentKey.childId]  + '-row'+ nextProps.index)&&  document.getElementById(item[nextProps.contentKey.childId]  + '-row'+ nextProps.index).style.display === 'none'){
            document.getElementById(item[nextProps.contentKey.childId]  + '-row'+ nextProps.index).style.display = 'none';
          }else{
            if(document.getElementById(item[nextProps.contentKey.childId]  + '-row'+ nextProps.index)){
              document.getElementById(item[nextProps.contentKey.childId]  + '-row'+ nextProps.index).style.display = display;
            }
             
          }
        });
      }
    }

  }


  tip = (item) => {
    
    let {
      mainId = 'pkSchedule',
      childId = 'pkScheduleItem',
      planStartDate = 'planStartDate',
      planEndDate = 'planEndDate',
      startDate = 'progressVO.startDate',
      endDate = 'progressVO.endDate',
      progress = 'progressVO.progress',
      planDays = 'planDays',
      completedStatus = 'completedStatus',
      name = 'name',
      code = 'code',
      managerName = 'managerName',
      isDelay = "isDelay"
    } = this.props.contentKey;
    return (
      <div>
        <p>{item[code]} {item[name]}</p>
        <p>负责人：{item[managerName]}  工期：{item[planDays]}日</p>
        <p>实际开始：{vendorsFmtDate(objectPath.get(item, startDate))}</p>
        <p>计划完成：{vendorsFmtDate(objectPath.get(item, planEndDate))}</p>
        <p>实际完成：{vendorsFmtDate(objectPath.get(item, endDate))}</p>
        <p style={{
          color: '#E51C23',
          fontSize: 12
        }}>{item[isDelay]? "延期" :null}</p>
      </div>
    )
  }

  content = (data = []) => {

    let {
      status = "day",
      year = [],
      contentKey,
      month,
      index = 0,
    } = this.props;

    let {
      mainId = 'pkSchedule',
      childId = 'pkScheduleItem',
      planStartDate = 'planStartDate',
      planEndDate = 'planEndDate',
      startDate = 'progressVO.startDate',
      endDate = 'progressVO.endDate',
      progress = 'progressVO.progress',
      planDays = 'planDays',
      completedStatus = 'completedStatus',
      name = 'name',
      code = 'code',
      managerName = 'managerName',
      dependPlans = 'dependPlans',
      dependPlansDeleted= 'dependPlansDeleted',
      pkMilestone = 'pkMilestone',
      pkParent = 'pkParent',
      isDelay = "isDelay"
    } = contentKey;

    return data.map((item) => {
      let { startTime, endTime } = this.handleDate(item);
      if(startTime && startTime.split("-")[2]){
        let curDayOfMonth = moment(vendorsFmtDate(item[planStartDate]), 'YYYY-M').daysInMonth();
       
        if (Number(startTime.split("-")[2]) === parseInt(curDayOfMonth/2)+ 1){//因为使用了display：flex, 所以当是中间数的时候。 取后一个
          startTime = moment(startTime).add(1, 'days').format("YYYY-M-D");
        }
      }
     
      let width = document.getElementById(startTime  + '-row'+ index)&&document.getElementById(startTime  + '-row'+ index).offsetWidth;//找到头部日期的宽度，计算本任务的宽
      width = startTime === month[0]+"-1" || startTime === month[0] ? width + 2 : width;//第一个是没有border的，所以主动 +2

      
      let rowHeight = document.getElementsByClassName("u-table-row") && document.getElementsByClassName("u-table-row")[0].offsetHeight;//找到该任务行，计算本任务的行的高，有默认42

      if (item.children) {
        return (
          <div
            style={{
              flex: 1
            }}
          >
            <div
              className = {'childNode'}
              style={{
                height: rowHeight ? rowHeight : 42,
                display: item.pkParent ? 'none' : 'flex',
              }}
              id={item[childId] +"-row"+ index}
            >

              <div
                className = {'childNodeContainer'}     
              >
                <Icon
                  type='uf-flag'
                  style={{
                    left:
                      moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                        moment( month[0]+"-1","YYYY-M-D"), status + 's'
                      ) * width,
                    visibility: item[pkMilestone] ? "visible" : 'hidden',
                  
                  }}
                  className={"ufFlag"}
                />
                <div
                  style={{
                    left:
                      moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                        moment( month[0]+"-1","YYYY-M-D"), status + 's'
                      ) * width + 15,
                    visibility: 'hidden'
                }}
                  className={'leftConnectLine'}
                  id={item[childId] +"-row"+index+ '_left'}
                >
                </div>
                <div
                  style={{
                    left:
                      moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                        moment( month[0]+"-1","YYYY-M-D"), status + 's'
                      ) * width + 15,
                    visibility: 'hidden'
                }}
                  className={'leftConnectLine'}
                  id={item[childId] +"-row"+index+  '_left_1'}
                >
                </div>
                <Tooltip 
                  inverse 
                  placement="top" 
                  overlay={this.tip(item)} 
                  container = {this.container?ReactDOM.findDOMNode(this.container).querySelector(".progressItem") : null}
                >
                  <div style={{
                      left:
                      moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                        moment( month[0]+"-1","YYYY-M-D"), status + 's'
                      ) * width,
                      position:'relative'
                  }} 
                  >
                    <div
                      className={'progressItem'}
                      style={{
                  
                        width:
                          (moment(endTime).diff(
                            moment(startTime),  status + 's'
                          ) + 1) * width - 28,//28是固定算出来的。小旗帜+左边的border+右边的宽
                        background :item[isDelay] ? ' #E51C23' : "#D4CFD4"
                      }}
                      id={item[childId]+"-row"+index}
                      ref={ref =>{this.container = ref}}
                    >
                      {objectPath.get(item, progress) ?
                        <div
                          className={'progress'}
                          style={{
                            width: ((moment(endTime).diff(
                              moment(startTime), status + 's'
                            ) + 1) * width - 28) *objectPath.get(item, progress)/100,
                            background :item[isDelay] ? ' #E51C23' : "#79b8ac"
                          }}
                          id={item[childId] +"-row"+index+ '_progress'}
                        >{objectPath.get(item, progress) }%</div> : null}

                      <div
                        id={item[childId] +"-row"+index+ '_right'}
                        className={'rightConnectLine'}
                        style={{
                          left: (moment(endTime).diff(
                            moment(startTime), status + 's'
                          ) + 1) * width - 28,//不显示， 但要占位置！存在前置任务，显示两个节点之间的连线，右折线}}
                          visibility: 'hidden'
                        }}//不显示， 但要占位置！存在前置任务，显示两个节点之间的连线，左折线
                      ></div>

                    </div>

                    <div style={{
                        display:item[pkParent] ? 'none':'flex', 
                        justifyContent:'space-between',
                        
                      }}
                    >
                      <div style={{visibility: 'visible', border:item[isDelay] ? '2px solid #E51C23' : "2px solid #D4CFD4", borderRight:'2px solid transparent', borderBottom:'2px solid transparent'}}>
                      </div>
                      <div style={{visibility: 'visible', border:item[isDelay] ? '2px solid #E51C23' : "2px solid #D4CFD4", borderLeft:'2px solid transparent', borderBottom:'2px solid transparent'}}>
                      </div>
                    </div>
                  </div>
                
                </Tooltip>
              </div>
            </div>
            {this.content(item.children)}
          </div>
        )
      }

      return (
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            flex: 1,
            display: item[pkParent] ? 'none' : 'flex',
          }}
          id={item[childId]+"-row"+index}

        >
          <div
            className = {'childNode'}
            style={{
              height: rowHeight ? rowHeight : 42,
              display: 'flex',
            }}
          >

            <div
               className = {'childNodeContainer'}
            >
              <Icon
                type='uf-flag'
                style={{
                  left:
                    moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                      moment(month[0]+"-1","YYYY-M-D"), status + 's'
                    ) * width,
                  visibility: item[pkMilestone] ? "visible" : 'hidden',
                }}
                className={"ufFlag"}
              />

              <div
                style={{
                  left:
                    moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                      moment(month[0]+"-1","YYYY-M-D"), status + 's'
                    ) * width + 15,
                  visibility:  'hidden'
              }}
                className={'leftConnectLine'}
                id={item[childId] +"-row"+index+ '_left'}
              >
              </div>
              <div
                style={{
                  left:
                    moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                      moment(month[0]+"-1","YYYY-M-D"), status + 's'
                    ) * width + 15,
                  visibility: 'hidden'
              }}
                className={'leftConnectLine'}
                id={item[childId]+"-row"+index + '_left_1'}
              >
              </div>
              <Tooltip 
                inverse 
                placement="top" 
                overlay={this.tip(item)}
                container = {this.container?ReactDOM.findDOMNode(this.container).querySelector(".progressItem") : null}
              >

                <div 
                  style={{
                    left:
                      moment(vendorsFmtDate(item[planStartDate]),"YYYY-M-D").diff(
                        moment( month[0]+"-1","YYYY-M-D"), status + 's'
                      ) * width,
                      position:'relative'
                  }} 
                >
                <div
                    className={'progressItem'}
                    style={{
      
                      width:
                        (moment(endTime).diff(
                          moment(startTime), status + 's'
                        ) +
                          1) *
                        width - 28,//28是固定算出来的。小旗帜+左边的border+右边的宽,
                        background :item[isDelay] ? ' #E51C23' : "#D4CFD4"
                    }}
                    id={item[childId]+"-row"+index+ '_progress'}
                    ref={ref =>{this.container = ref;}}
                  >

                    {objectPath.get(item, progress) ?
                      <div
                        className={'progress'}
                        style={{
                          width: ((moment(endTime).diff(
                            moment(startTime), status + 's'
                          ) + 1) * width - 28) *objectPath.get(item, progress)/100,
                          background :item[isDelay] ? ' #E51C23' : "#79b8ac"
                        }}>{objectPath.get(item, progress) }%</div> : null}
                      
                    <div
                      className={'rightConnectLine'}
                      id={item[childId] +"-row"+index+ '_right'}
                      style={{
                        left: (moment(endTime).diff(
                          moment(startTime),  status + 's'
                        ) +
                          1) *
                          width - 28,
                        visibility: 'hidden'//不显示， 但要占位置！存在前置任务，显示两个节点之间的连线，左折线
                      }}
                    ></div>
                  </div>
                  <div style={{
                      display:item[pkParent] ? 'none':'flex', 
                      justifyContent:'space-between',
                      }}
                    >
                      <div style={{visibility: 'visible', border:item[isDelay] ? '2px solid #E51C23' : "2px solid #D4CFD4", borderRight:'2px solid transparent', borderBottom:'2px solid transparent'}}>
                      </div>
                      <div style={{visibility: 'visible', border:item[isDelay] ? '2px solid #E51C23' : "2px solid #D4CFD4", borderLeft:'2px solid transparent', borderBottom:'2px solid transparent'}}>
                      </div>
                  </div>
               </div>
              </Tooltip>
              
            </div>
          </div>
        </div>
      )
    })
  }

  //分割时间
  handleDate = data => {
    let startTime = '',
      endTime = '',
      depPlanStartTime = '', depPlanEndTime = '',
      { status } = this.props,
      { planStartDate = 'planStartDate', planEndDate = 'planEndDate' } = this.props.contentKey;

    if (status === 'year') {//year
      startTime = moment(data[planStartDate]).format('YYYY')
      endTime = moment(data[planEndDate]).format('YYYY')

    } else if (status === 'month') {//month
      startTime = moment(data[planStartDate]).format('YYYY-M')
      endTime = moment(data[planEndDate]).format('YYYY-M')
    } else {//day
      startTime = moment(data[planStartDate]).format('YYYY-M-D')
      endTime = moment(data[planEndDate]).format('YYYY-M-D')
    }
    depPlanStartTime = startTime;
    depPlanEndTime = endTime;
    return { startTime, endTime,  depPlanStartTime, depPlanEndTime }
  }

  render() {
    let {
      data = [],
      onExpand = false,
      expandRecord = {},
      status,
      month,
      index,
    } = this.props;
    return (
      <div>
        <div
          style={{
            width: document.getElementById('header-row'+index) && document.getElementById('header-row'+index).scrollWidth
          }}
        >
          {data.length ? this.content(data) : null}
        </div>
        <div style={{ display: 'flex' }}>
          {data.length && <GanttDependPlansContent
            data={data}
            onExpand={onExpand}
            expandRecord={expandRecord}
            contentKey={{ ...this.props.contentKey }}
            handleDate={(prams) => this.handleDate.call(this, prams)}
            status={status}
            month = {month}
            index = {index}
          />}
        </div>
      </div>
    )
  }
}
//控制前置任务的连接线的子组件
class GanttDependPlansContent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      data: []
    }
  }

  componentDidMount() {
    this.setState({
      data: this.props.data
    })
  }
  
  content = (data = [], res = [], preHeight = 0) => {
    let {
      childId = 'pkScheduleItem',
      planStartDate = 'planStartDate',
      planEndDate = "planEndDate",
      dependPlans = 'dependPlans',
      dependPlansDeleted= 'dependPlansDeleted',
      pkParent = 'pkParent'
    } = this.props.contentKey;

    let {
      status,
      month,
      index
    } = this.props
    data.map((item) => {
      let { startTime, endTime } = this.props.handleDate(item);


      if(startTime && startTime.split("-")[2]){
        let curDayOfMonth = moment(vendorsFmtDate(item[planStartDate]), 'YYYY-M').daysInMonth();
       
        if (Number(startTime.split("-")[2]) === parseInt(curDayOfMonth/2)+ 1){//因为使用了display：flex, 所以当是中间数的时候。 取后一个
          startTime = moment(startTime).add(1, 'days').format('YYYY-M-D');
        }
      }
     
   
      let width = document.getElementById(startTime + '-row'+index) && document.getElementById(startTime + '-row'+index).offsetWidth || 50;//找到头部日期的宽度，计算本任务的宽
      width = startTime === month[0]+"-1" || startTime === month[0] ? width + 2 : width;//第一个是没有border的，所以主动 +2

      let childTop = 0;
      let dependTop = 0;
      let mapData =  item[dependPlans] ? item[dependPlans] : item[dependPlansDeleted]?  item[dependPlansDeleted]:[];

      mapData.map((depPlanItem) => {
        let { depPlanStartTime, depPlanEndTime } = this.props.handleDate(depPlanItem);
        dependTop =
          document.getElementById(depPlanItem[childId] + '-row'+ index) &&
          document.getElementById(depPlanItem[childId]+ '-row'+ index).offsetTop;

        childTop =
          document.getElementById(item[childId] + '-row'+ index) &&
          document.getElementById(item[childId] + '-row'+ index).offsetTop;

        if(childTop === 0 && item[pkParent]){
          return;
        }
       
        if( document.getElementById(item[childId]+ '-row'+ index) && document.getElementById(item[childId]+ '-row'+ index).style.display ==='none'||!(document.getElementById(item[childId] + '-row'+ index)&&document.getElementById(item[childId] + '-row'+ index).style.display)){
       //   document.getElementById(item[childId]+"_right").style.visibility ='hidden'
          return;
        }
        let curDistance = childTop - dependTop;
        if(curDistance < 0){
          curDistance = -curDistance;
        }
        if (preHeight < curDistance) {
          preHeight = curDistance - 20;
        }
        let display = "visible";
        if(item[dependPlansDeleted]){//if(depPlanItem.hasDeleted){
          preHeight = 0;
          display = "hidden";
        }else{
          display = "visible";
        }
        
        if(  childTop - dependTop < 0){
              
       
          document.getElementById(item[childId] + '-row'+ index + '_right').style.height = preHeight + 2 +'px';

          document.getElementById(item[childId]  + '-row'+ index+ '_right').style.width = preHeight ? 12 + 'px' : '0px';
          document.getElementById(item[childId] + '-row'+ index + '_right').style.borderTop = preHeight ? '1px solid #8C8E8D' : '0px';

          document.getElementById(item[childId]  + '-row'+ index+ '_right').style.visibility = display;
          document.getElementById(item[childId] + '-row'+index + '_left').style.visibility = 'hidden';
        //  document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_left').style.visibility = 'hidden';

          document.getElementById(depPlanItem[childId] + '-row'+ index+ '_left_1').style.visibility = 'visible';

          if(moment(depPlanStartTime, "YYYY-M-D").isAfter(moment(endTime, "YYYY-M-D"))){
            document.getElementById(depPlanItem[childId] + '-row'+ index+ '_left_1').style.visibility = 'visible';
          //  document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_left').style.visibility = 'hidden';
            document.getElementById(depPlanItem[childId]  + '-row'+ index+  '_left_1').style.transform =  'scale(-1,1)';//水平翻转
            document.getElementById(depPlanItem[childId] + '-row'+ index+  '_left_1').style.transformOrigin = 'left';//水平翻转，以左边为基点
            
            document.getElementById(depPlanItem[childId]  + '-row'+ index+  '_left_1').style.width = (moment(vendorsFmtDate(depPlanItem[planStartDate]), "YYYY-M-D").diff(
              moment(vendorsFmtDate(item[planEndDate]), "YYYY-M-D"), status + 's'
            ) - 1) * width + 16 +1+ 'px'
          }else{
            document.getElementById(depPlanItem[childId]  + '-row'+ index+  '_left').style.visibility = 'visible';
            document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_left_1').style.visibility = 'hidden';
            document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_left').style.width =  (moment(vendorsFmtDate(depPlanItem[planStartDate]), "YYYY-M-D").diff(
              moment(vendorsFmtDate(item[planEndDate]), "YYYY-M-D"), status + 's'
            ) + 1) * width - 16 + 'px' //16是border+小旗子
           
          }
        
        }else{
          document.getElementById(depPlanItem[childId] + '-row'+ index + '_right').style.height = preHeight + 2 + 'px';

          document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_right').style.width = preHeight ? 12 + 'px' : '0px';
          document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_right').style.borderTop = preHeight ? '1px solid #8C8E8D' : '0px';
          
          document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_right').style.visibility = display;
         // document.getElementById(depPlanItem[childId]  + '-row'+ index+ '_left').style.visibility = 'hidden';
    
          if(moment(startTime ,'YYYY-M-D' ).isAfter(moment(depPlanEndTime,'YYYY-M-D'))){
            document.getElementById(item[childId]  + '-row'+ index+  '_left_1').style.visibility = 'visible';
            document.getElementById(item[childId]  + '-row'+ index+  '_left').style.visibility = 'hidden';
            document.getElementById(item[childId] + '-row'+ index +  '_left_1').style.transform =  'scale(-1,1)';//水平翻转
            document.getElementById(item[childId]  + '-row'+ index+  '_left_1').style.transformOrigin = 'left';//水平翻转，以左边为基点
            
            document.getElementById(item[childId] + '-row'+ index+  '_left_1').style.width = (moment(vendorsFmtDate(item[planStartDate]),'YYYY-M-D').diff(
              moment(vendorsFmtDate(depPlanItem[planEndDate]),'YYYY-M-D'), status + 's'
            ) - 1) * width + 16 +1+ 'px';
          }else{
            document.getElementById(item[childId] + '-row'+ index+  '_left').style.visibility = 'visible';
            document.getElementById(item[childId] + '-row'+ index+  '_left_1').style.visibility = 'hidden';
            document.getElementById(item[childId] + '-row'+ index+ '_left').style.width = (moment(vendorsFmtDate(depPlanItem[planEndDate]),'YYYY-M-D').diff(
              moment(vendorsFmtDate(item[planStartDate]),'YYYY-M-D'), status + 's'
            ) + 1) * width - 16 + 'px' //16是border+小旗子
           
          }
        
        }
        
      })

      if (item.children) {
        this.content(item.children, res, preHeight)
      }
    })
    return res
  }

  render() {
    return <div>{this.state.data.length ? this.content(this.props.data) : null}</div>
  }
}
